package com.xj.nrpc.handler;

import com.alibaba.fastjson.JSONObject;
import com.xj.nrpc.core.handler.param.ServerRequest;
import com.xj.nrpc.core.media.Media;
import com.xj.nrpc.core.util.ResponseEntity;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

public class ServerChannelHandler extends ChannelInboundHandlerAdapter {

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

		System.out.println(msg.toString() + " i am server" + System.currentTimeMillis());
		if ("ping".equals(msg.toString())) {
			return;
		}
		ServerRequest req = JSONObject.toJavaObject(JSONObject.parseObject(msg.toString()), ServerRequest.class);

		Media media = Media.newInstance();
		ResponseEntity resp = media.process(req);
		ctx.channel().writeAndFlush(JSONObject.toJSONString(resp));
		ctx.channel().writeAndFlush("\r\n");

	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if (evt instanceof IdleStateEvent) {
			IdleStateEvent idle = (IdleStateEvent) evt;
			if (idle.state().equals(IdleState.READER_IDLE)) {
				ctx.channel().close();
			} else if (idle.state().equals(IdleState.WRITER_IDLE)) {
				// TODO 处理业务逻辑
			} else if (idle.state().equals(IdleState.ALL_IDLE)) {
				ctx.channel().writeAndFlush("ping\r\n");
			}
		}

	}

}
